<template>
    <div>
        <el-card>
            <el-button type="primary" @click="addTradeMark" icon="Plus" v-has="`btn.Trademark.add`">添加品牌</el-button>
            <el-table border :data="trademarkArr" style="margin: 10px 0px;">
                <el-table-column label="序号" width="80px" align="center" type="index">
                </el-table-column>
                <el-table-column label="品牌名称">
                    <template #="{ row, $index }">
                        <pre>{{ row.tmName }}</pre>
                    </template>
                </el-table-column>
                <el-table-column label="品牌LOGO">
                    <template #="{ row, $index }">
                        <img :src="row.logoUrl" alt="" style="width: 100px;height: 100px;">
                    </template>
                </el-table-column>
                <el-table-column label="品牌操作">
                    <template #="{ row, $index }">
                        <el-button type="primary" size="small" @click="updateTradeMark(row)" icon="Edit"></el-button>
                        <el-popconfirm :title="`你确定要删除${row.tmName}吗？`" width="200" icon="Delete"
                            @confirm="removeTradeMark(row.id)">
                            <template #reference>
                                <el-button type=" primary" size="small" @click="" icon="Delete"></el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination v-model:current-page="pageNo" v-model:page-size="limit" :page-sizes="[3, 5, 7, 9]"
                :background="true" layout=" prev, pager, next, jumper,->,sizes,total" :total="total"
                @current-change="getTradeMark" @size-change="sizeChange" />
        </el-card>
        <!-- 对话框组件，在添加和修改时使用 -->
        <el-dialog v-model="dialogFormVisible" :title="trademarkParams.id ? '修改品牌' : '添加品牌'">
            <el-form style="width: 80%;" :model="trademarkParams" :rules="rules" ref="formRef">
                <el-form-item label="品牌名称" label-width="80px" prop="tmName">
                    <el-input placeholder="请您输入品牌名称" v-model="trademarkParams.tmName"></el-input>
                </el-form-item>
                <el-form-item label="品牌LOGO" label-width="80px" prop="logoUrl">
                    <el-upload class="avatar-uploader" action="/api/admin/product/fileUpload" :show-file-list="false"
                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="trademarkParams.logoUrl" :src="trademarkParams.logoUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button type="" @click="cancel">取消</el-button>
                <el-button type="primary" @click="confirm">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang='ts' name="TradeMark">
import { ref, onMounted, reactive } from 'vue';
import { reqTradeMark, reqAddOrUpdateTradeMark, reqRemoveTradeMark } from '@/api/product/trademark';
import type { Recodes, TradeMarkResponseData, TradeMark } from "@/api/product/trademark/type";
import { ElMessage, type UploadProps } from 'element-plus'
//分页器当前页码
let pageNo = ref<number>(1)
//每一页展示多少个数据
let limit = ref<number>(3)
let total = ref<number>(0)
//存储已有品牌的数据
let trademarkArr = ref<Recodes>([])
//控制对话框的显示与隐藏
let dialogFormVisible = ref(false)
//定义收集新增品牌数据
let trademarkParams = reactive<TradeMark>({
    tmName: '',
    logoUrl: ''
})
//获取el-form组件实例
let formRef = ref()
onMounted(() => {
    pageNo.value = 1
    getTradeMark()
})
//获取已有品牌的函数
const getTradeMark = async (pager = 1) => {
    pageNo.value = pager
    let result: TradeMarkResponseData = await reqTradeMark(pageNo.value, limit.value)
    if (result.code == 200) {
        total.value = result.data.total
        trademarkArr.value = result.data.records
    }
}
//每一页展示的数据个数
const sizeChange = () => {
    getTradeMark();
}
//添加
const addTradeMark = () => {
    dialogFormVisible.value = true
    //添加前先清空数据
    trademarkParams.id = 0;
    trademarkParams.tmName = ''
    trademarkParams.logoUrl = ''
    formRef.value?.clearValidate('logoUrl')
    formRef.value?.clearValidate('tmName')
}
// 修改
const updateTradeMark = (row: TradeMark) => {
    dialogFormVisible.value = true
    //展示数据
    //ES6语法合并对象
    Object.assign(trademarkParams, row)
    formRef.value?.clearValidate('logoUrl')
    formRef.value?.clearValidate('tmName')
}
//对话框的按钮
const cancel = () => {
    dialogFormVisible.value = false;
}
const confirm = async () => {
    //在你发请求之前需要对整个表单进行校验,校验通过后在执行后面的语句
    await formRef.value.validate();
    let result = await reqAddOrUpdateTradeMark(trademarkParams)
    console.log(trademarkParams);
    if (result.code == 200) {
        dialogFormVisible.value = false;
        ElMessage({
            type: 'success',
            message: trademarkParams.id ? '修改品牌成功' : ' 添加品牌成功'
        })
        getTradeMark(trademarkParams.id ? pageNo.value : 1);
    } else {
        ElMessage({
            type: 'error',
            message: trademarkParams.id ? ' 修改品牌失败' : '添加品牌失败'
        })
    }

}
//上传图片之前触发的钩子函数
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    //约束文件大小、类型
    if (rawFile.type == 'image/png' || rawFile.type == 'image/jpeg' || rawFile.type == 'image/gif') {
        if (rawFile.size / 1024 / 1024 < 4) {
            return
        } else {
            ElMessage({
                type: 'error',
                message: '上传文件大小大于4 M '
            })
        }
    } else {
        ElMessage({
            type: 'error',
            message: '上传的文件务必是jpg,gif,jpeg'
        })
        return false
    }
}
//图片上传成功
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,//即为当前这次上传图片post请求服务器返回的数据
    uploadFile
) => {
    trademarkParams.logoUrl = response.data;
    formRef.value.clearValidate('logoUrl')
}
//自定义校验规则方法
const validatorTmName = (rule: any, value: any, callback: any) => {
    if (value.trim().length >= 2) {
        callback();
    } else {
        callback(new Error('品牌名称大于等于两位'))
    }
}
const validatorLogoUrl = (rule: any, value: any, callback: any) => {
    //如果图片上传
    if (value) {
        callback();
    } else {
        callback(new Error('LOGO图片务必上传'))
    }
}
//表单校验规则对象
const rules = {
    tmName: [
        { required: true, trigger: 'blur', validator: validatorTmName }
    ],
    logoUrl: [
        { required: true, validator: validatorLogoUrl }
    ]
}
//气泡确认框确定按钮的回调
const removeTradeMark = async (id: number) => {
    let result = await reqRemoveTradeMark(id)
    if (result.code == 200) {
        ElMessage({
            type: 'success',
            message: '删除品牌成功'
        })
        getTradeMark(trademarkArr.value.length > 1 ? pageNo.value : pageNo.value - 1);
    } else {
        ElMessage({
            type: 'success',
            message: '删除品牌失败'
        })
    }
}
</script>

<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>